#!/bin/bash

# SSL证书生成脚本
# 用于生成自签名证书或Let's Encrypt证书

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}  SSL证书生成脚本${NC}"
    echo -e "${BLUE}================================${NC}"
}

# 生成自签名证书
generate_self_signed() {
    local domain=${1:-"localhost"}
    local email=${2:-"admin@localhost"}
    
    print_message "生成自签名SSL证书..."
    print_warning "自签名证书仅用于开发环境，浏览器会显示安全警告"
    
    # 创建SSL目录
    mkdir -p nginx/ssl
    
    # 生成私钥
    openssl genrsa -out nginx/ssl/key.pem 2048
    
    # 生成证书签名请求
    openssl req -new -key nginx/ssl/key.pem -out nginx/ssl/cert.csr -subj "/C=CN/ST=State/L=City/O=Organization/OU=OrgUnit/CN=$domain/emailAddress=$email"
    
    # 生成自签名证书
    openssl x509 -req -days 365 -in nginx/ssl/cert.csr -signkey nginx/ssl/key.pem -out nginx/ssl/cert.pem
    
    # 清理临时文件
    rm nginx/ssl/cert.csr
    
    # 设置权限
    chmod 600 nginx/ssl/key.pem
    chmod 644 nginx/ssl/cert.pem
    
    print_message "自签名证书生成完成"
    print_message "证书文件: nginx/ssl/cert.pem"
    print_message "私钥文件: nginx/ssl/key.pem"
}

# 使用Let's Encrypt生成证书
generate_letsencrypt() {
    local domain=${1:-""}
    local email=${2:-""}
    
    if [ -z "$domain" ] || [ -z "$email" ]; then
        print_error "请提供域名和邮箱地址"
        echo "使用方法: $0 letsencrypt <domain> <email>"
        exit 1
    fi
    
    print_message "使用Let's Encrypt生成SSL证书..."
    print_message "域名: $domain"
    print_message "邮箱: $email"
    
    # 检查certbot是否安装
    if ! command -v certbot &> /dev/null; then
        print_message "安装certbot..."
        sudo apt-get update
        sudo apt-get install -y certbot python3-certbot-nginx
    fi
    
    # 创建SSL目录
    mkdir -p nginx/ssl
    
    # 生成证书
    sudo certbot certonly --standalone -d "$domain" --email "$email" --agree-tos --non-interactive
    
    # 复制证书到项目目录
    sudo cp "/etc/letsencrypt/live/$domain/fullchain.pem" nginx/ssl/cert.pem
    sudo cp "/etc/letsencrypt/live/$domain/privkey.pem" nginx/ssl/key.pem
    
    # 设置权限
    sudo chown $USER:$USER nginx/ssl/cert.pem nginx/ssl/key.pem
    chmod 644 nginx/ssl/cert.pem
    chmod 600 nginx/ssl/key.pem
    
    print_message "Let's Encrypt证书生成完成"
    print_message "证书文件: nginx/ssl/cert.pem"
    print_message "私钥文件: nginx/ssl/key.pem"
    
    # 设置自动续期
    print_message "设置证书自动续期..."
    (crontab -l 2>/dev/null; echo "0 12 * * * /usr/bin/certbot renew --quiet --post-hook 'docker-compose restart nginx'") | crontab -
    print_message "证书自动续期已设置"
}

# 显示帮助信息
show_help() {
    echo "使用方法: $0 [命令] [参数]"
    echo ""
    echo "命令:"
    echo "  self-signed [域名] [邮箱]    生成自签名证书"
    echo "  letsencrypt <域名> <邮箱>    使用Let's Encrypt生成证书"
    echo "  help                        显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 self-signed localhost admin@localhost"
    echo "  $0 letsencrypt example.com admin@example.com"
}

# 主函数
main() {
    print_header
    
    COMMAND=${1:-"help"}
    
    case $COMMAND in
        "self-signed")
            generate_self_signed "$2" "$3"
            ;;
        "letsencrypt")
            generate_letsencrypt "$2" "$3"
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            print_error "未知命令: $COMMAND"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
